package com.asktgapp.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.asktgapp.MyConstant;
import com.asktgapp.R;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoFragment;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;


/**
 * time:2017/11/6
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */
@SuppressLint("ValidFragment")
public class SelectPhotoDialogFragment extends TakePhotoFragment implements View.OnClickListener {

    private int limit;
    private TakePhoto takePhoto;
    private File mFile;
    private Uri imageUri;

    private setResult mResult;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.take_photo) {
            if ((limit - MyConstant.limit == 0)) {
                Toast.makeText(getActivity(), "选则图片达到上限", Toast.LENGTH_LONG).show();
            } else {
                CropOptions cropOptions=new CropOptions.Builder().setAspectX(10).setAspectY(16).setWithOwnCrop(false).create();

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String[] permissions = new String[]{Manifest.permission.CAMERA};
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        takePhoto.onPickFromCapture(imageUri);
//                        takePhoto.onPickFromCaptureWithCrop(imageUri,cropOptions);
                    } else {
                        ActivityCompat.requestPermissions(getActivity(), permissions, 001);
                    }
                } else {
                    takePhoto.onPickFromCapture(imageUri);
//                    takePhoto.onPickFromCaptureWithCrop(imageUri,cropOptions);
                }
            }
        } else if (i == R.id.select_photo) {

            if ((limit - MyConstant.limit == 0)) {
                Toast.makeText(getActivity(), "选则图片达到上限", Toast.LENGTH_LONG).show();
                dismiss();
            } else {
                takePhoto.onPickMultiple(limit - MyConstant.limit);
            }
        } else if (i == R.id.cancle) {
            dismiss();
        }
    }


    public interface setResult {
        void setResult(ArrayList<TImage> mImages);
    }

    @SuppressLint("ValidFragment")
    public SelectPhotoDialogFragment(setResult result, int limit) {
        mResult = result;
        this.limit = limit;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // TODO: 2018/3/6 这里要替换
            imageUri = FileProvider.getUriForFile(getActivity(), "com.asktgapp.fileprovider", file);
        }else {
            imageUri = Uri.fromFile(file);
        }
        takePhoto = getTakePhoto();
        CompressConfig config = new CompressConfig.Builder().create();
        takePhoto.onEnableCompress(config, false);
        Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialogfragment_select_img);
        dialog.findViewById(R.id.take_photo).setOnClickListener(this);
        dialog.findViewById(R.id.select_photo).setOnClickListener(this);
        dialog.findViewById(R.id.cancle).setOnClickListener(this);
//        takePhoto.onPickFromCapture(imageUri);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams p = window.getAttributes();
        WindowManager m = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        window.setBackgroundDrawableResource(R.drawable.dialog_bg);
        Display d = m.getDefaultDisplay();
        p.width = (int) (d.getWidth() * 0.9);
        p.gravity = Gravity.BOTTOM;
        p.windowAnimations = R.style.popwin_anim_style;
        window.setAttributes(p);
        return dialog;
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeSuccess(TResult result) {
        dismiss();
        ArrayList<TImage> images = result.getImages();
        mResult.setResult(images);
//        super.takeSuccess(result);

    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (PermissionUtils.verifyPermissions(grantResults)) {
//            takePhoto.onPickFromCapture(imageUri);
//        } else {
//            if (!PermissionUtils.shouldShowRequestPermissionRationale(getActivity(), permissions)) {
//                Toast.makeText(getActivity(), "权限已被拒绝,请在设置-应用-权限中打开", Toast.LENGTH_SHORT).show();
//            }
//        }
    }
}
